<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.9/theme-chalk/index.css">
</head>
<body>
<div id="app">
  <el-page-header style="background-color: #0096dc;color: white;line-height: 60px"
                  @back="goBack" content="添加轮播图页面">
  </el-page-header>
  <!--action:设置文件上传的路径
      limit:设置上传图片的数量
      name:设置上传文件的参数名称
  -->
  <el-upload
          action="/upload"
          limit="1"
          name="picFile"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="handleSuccess"
          :on-remove="handleRemove">
    <i class="el-icon-plus"></i>
  </el-upload>
  <el-dialog :visible.sync="dialogVisible">
    <img width="100%" :src="dialogImageUrl" alt="">
  </el-dialog>
  <input type="text" placeholder="图片描述" v-model="b.des">
  <el-button type="success" @click="add()">上传图片</el-button>
</div>
</body>
<!--引入axios和vue框架文件-->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<!-- import Vue before Element -->
<script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script>
<!-- import JavaScript -->
<script src="https://cdn.staticfile.org/element-ui/2.15.9/index.min.js"></script>
<script>
  let v = new Vue({
    el: '#app',
    data: function () {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        b: {des: "", url: ""}
      }
    },
    methods: {
      add() {
        if (v.b.url == "") {
          alert("请选择上传的图片!");
          return;
        }
        //发出异步请求
        axios.post("/insert",v.b).then(function () {
          alert("上传完成!");
          location.href = "/";
        })
      },
      handleSuccess(response, file, fileList) {
        //response代表服务器响应的数据(图片url)
        //file表示上传成功的文件对象(包含文件的相关信息,其中file.response等于上面的response)
        //fileList 上传多个图片时会用到,是一个数组里面装多个file对象
        console.log(response);
        v.b.url = response;
      },
      goBack() {
        //返回上一页面
        history.back();
      },
      handleRemove(file, fileList) {
        v.b.url = "";
        // file.response 代表上传文件成功时 服务器响应的内容(图片路径)
        console.log(file.response, fileList);
        //发出删除图片的请求
        axios.get("/remove?url=" + file.response).then(function () {
          console.log("删除完成!");
        })
      },
      handlePictureCardPreview(file) {
        console.log("file=" + file);
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    }
  })
</script>
</html>